package com.sense.kukoo.biz_media.view

import android.graphics.drawable.Drawable
import android.os.Build
import android.os.Bundle
import android.view.View
import android.widget.SeekBar
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.sense.kukoo.biz_media.R
import com.sense.kukoo.biz_media.databinding.BizMediaActivityMediaControlerBinding
import com.sense.kukoo.biz_media.vm.MediaControlerViewModel
import com.sense.kukoo.common.constant.ARouterUrl
import com.sense.kukoo.common.event.LoginSuccessEvent
import com.sense.kukoo.common.event.LogoutEvent
import com.sense.kukoo.common.event.SubscriptionChangedEvent
import com.sense.kukoo.common.media.Kukoo
import com.sense.kukoo.common.media.bean.LocalMediaListItemBean
import com.sense.kukoo.common.media.watcher.UserWatcher
import com.sense.kukoo.common.mvvm.view.BaseMvvmActivity
import com.sense.kukoo.common.utils.ApplicationContext
import com.sense.kukoo.common.wiget.dialog.BottomLoginDialog
import com.sense.kukoo.common.wiget.dialog.TimerSelectionPopupWindow
import com.sense.kukoo.lib_logger.LoggerManager
import com.sense.kukoo.lib_picture.config.GlideConfig
import com.sense.kukoo.lib_picture.loader.Monet
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

@Route(path = ARouterUrl.ROUTE_MEDIA_MODULE_MEDIA_CONTROLER_ACTIVITY)
class MediaControlerActivity : BaseMvvmActivity<MediaControlerViewModel, BizMediaActivityMediaControlerBinding>() {

    private val TAG: String = javaClass.simpleName
    private val mAnimHeight:Float = 800f
    private val mAnimTime:Long = 400

    private var state = UserWatcher.MusicStateWatcher.STATE_NOT_PLAYING
    private var speed: Float = UserWatcher.MusicStateWatcher.SPEED_1P0
    private var isSeekBarTracking = false
    private var isSubscribe:Boolean = false
    private var isLike:Boolean = false
    private var isZoomOutCardView:Boolean = false
    private lateinit var mCurrentMusic: LocalMediaListItemBean

    private lateinit var drawable_thumb_red: Drawable
    private lateinit var drawable_thumb_black: Drawable
    private lateinit var drawable_progress_red: Drawable
    private lateinit var drawable_progress_black: Drawable

    override fun getLayoutId(): Int = R.layout.biz_media_activity_media_controler

    override fun getViewModelClass(): Class<MediaControlerViewModel> = MediaControlerViewModel::class.java

    override fun responseVM(action: Int) {}

    override fun initData() {
        mBinding.lifecycleOwner = this
        mBinding.vm = mViewModel
        //
        mBinding.ivBack.setOnClickListener {
            animateToFinish()
        }
        mBinding.ivShare.setOnClickListener {
            val alias : String = mCurrentMusic.titleOfChapter()
            val type : Int = /*mCurrentMusic.type*/ 0
            val subTitle : String = mCurrentMusic.titleOfChapter()
            val author : String = mCurrentMusic.authorOfBook()
            val bookUrl : String = mCurrentMusic.getAudioUrl()
            val imgUrl : String = mCurrentMusic.coverOfChapter()
            ARouter.getInstance()
                .build(ARouterUrl.ROUTE_SHARE_MODULE_SHARE_ACTIVITY)
                .withString(ARouterUrl.KEY_SHARE_BOOK_TITLE, alias)
                .withInt(ARouterUrl.KEY_SHARE_BOOK_TYPE, type)
                .withString(ARouterUrl.KEY_SHARE_BOOK_SUB_TITLE, subTitle)
                .withString(ARouterUrl.KEY_SHARE_BOOK_AUTHOR, author)
                .withString(ARouterUrl.KEY_SHARE_BOOK_URL, bookUrl)
                .withString(ARouterUrl.KEY_SHARE_BOOK_IMAGE_URL, imgUrl)
                .navigation()
        }
        mBinding.ivBtnBackward.setOnClickListener {
            Kukoo.input.seekBy(-15*1000)
        }
        mBinding.ivBtnForward.setOnClickListener {
            Kukoo.input.seekBy(30*1000)
        }
        mBinding.ivBtnPlay.setOnClickListener {
            LoggerManager.d(TAG, "iv_btn_play.setOnClickListener state=${state}")
            when (state) {
                UserWatcher.MusicStateWatcher.STATE_PREPARE,
                UserWatcher.MusicStateWatcher.STATE_ERROR_RETRYING,
                UserWatcher.MusicStateWatcher.STATE_SEEKING,
                UserWatcher.MusicStateWatcher.STATE_PLAYING ->{
                    Kukoo.input.pause()
                }
                UserWatcher.MusicStateWatcher.STATE_PAUSE ->{
                    Kukoo.input.start()
                }
                else ->{
                    LoggerManager.e(TAG, "iv_btn_play.setOnClick state=${state} 不响应")
                }
            }
        }
        mBinding.ivBtnPlaylist.setOnClickListener {
            ARouter.getInstance()
                .build(ARouterUrl.ROUTE_MEDIA_MODULE_MEDIA_LIST_ACTIVITY)
                .navigation()
        }
        mBinding.tvBtnTimes.setOnClickListener {
            var newSpeed = UserWatcher.MusicStateWatcher.SPEED_1P0
            when (speed) {
                UserWatcher.MusicStateWatcher.SPEED_1P0 -> {
                    newSpeed = UserWatcher.MusicStateWatcher.SPEED_1P2
                }
                UserWatcher.MusicStateWatcher.SPEED_1P2 -> {
                    newSpeed = UserWatcher.MusicStateWatcher.SPEED_1P5
                }
                UserWatcher.MusicStateWatcher.SPEED_1P5 -> {
                    newSpeed = UserWatcher.MusicStateWatcher.SPEED_2P0
                }
                UserWatcher.MusicStateWatcher.SPEED_2P0 -> {
                    newSpeed = UserWatcher.MusicStateWatcher.SPEED_0P8
                }
                UserWatcher.MusicStateWatcher.SPEED_0P8 -> {
                    newSpeed = UserWatcher.MusicStateWatcher.SPEED_1P0
                }
                else -> {}
            }
            //版本适配
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
                Kukoo.input.setSpeed(newSpeed)
            }
        }
        mBinding.llBtnTimer.setOnClickListener {
            TimerSelectionPopupWindow.create(mBinding.root)
                .setListener {
                    Kukoo.input.setTimer(it)
                }.show(mBinding.llBtnTimer)
        }
        mBinding.ivBtnHeart.setOnClickListener {
            if (BottomLoginDialog.autoCheckAndLogin(this)){
                mViewModel.switchLikeState()
            }
        }
        mBinding.seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            var userProgress = 0

            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                if (fromUser) {
                    userProgress = progress
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {
                isSeekBarTracking = true
                mBinding.tvTimeCurrent.setTextColor(ApplicationContext.getColor(com.sense.kukoo.common.R.color.dialog_btn_text_color_red))
                mBinding.tvTimeTotal.setTextColor(ApplicationContext.getColor(com.sense.kukoo.common.R.color.dialog_btn_text_color_red))
                mBinding.seekBar.thumb = drawable_thumb_red
                val bounds = mBinding.seekBar.progressDrawable.bounds
                mBinding.seekBar.progressDrawable = drawable_progress_red
                mBinding.seekBar.progressDrawable.bounds = bounds
            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                isSeekBarTracking = false
                Kukoo.input.seekTo(userProgress)
                mBinding.tvTimeCurrent.setTextColor(ApplicationContext.getColor(com.sense.kukoo.common.R.color.common_text_tab_gray))
                mBinding.tvTimeTotal.setTextColor(ApplicationContext.getColor(com.sense.kukoo.common.R.color.common_text_tab_gray))
                mBinding.seekBar.thumb = drawable_thumb_black
                val bounds = mBinding.seekBar.progressDrawable.bounds
                mBinding.seekBar.progressDrawable = drawable_progress_black
                mBinding.seekBar.progressDrawable.bounds = bounds
            }
        })
        mBinding.bgBtnSubscribe.setOnClickListener {
            if (BottomLoginDialog.autoCheckAndLogin(this)){
                mViewModel.switchSubscription()
            }
        }
        mBinding.tvTitleFirst.setOnClickListener {
            /*ARouter.getInstance()
                .build(ARouterUrl.ROUTE_MEDIA_MODULE_MEDIA_LIST_DETAIL_ACTIVITY)
                .withString(ARouterUrl.KEY_BOOK_ID_STR, ""+ mCurrentMusic.idOfBooks())
                .navigation()*/
        }
        bindData(mViewModel.data_subscribeBtnVisibility){
            mBinding.bgBtnSubscribe.visibility = if(it) View.VISIBLE else View.GONE
        }
        bindData(mViewModel.data_subscribeBtnState){
            setSubscribeBtnState(it)
        }
        bindData(mViewModel.data_likeBtnVisibility){
            mBinding.ivBtnHeart.visibility = if(it) View.VISIBLE else View.GONE
        }
        bindData(mViewModel.data_likeBtnState){
            setLikeState(it)
        }
        //
        mBinding.tvTitleFirst.requestFocus()
    }

    override fun initView() {
        drawable_thumb_red = ApplicationContext.getResources().getDrawable(com.sense.kukoo.common.R.drawable.common_icon_seekbar_thumb_red)
        drawable_thumb_black = ApplicationContext.getResources().getDrawable(com.sense.kukoo.common.R.drawable.common_icon_seekbar_thumb_black)
        drawable_progress_red = ApplicationContext.getResources().getDrawable(com.sense.kukoo.common.R.drawable.common_layer_seekbar_progress_red)
        drawable_progress_black = ApplicationContext.getResources().getDrawable(com.sense.kukoo.common.R.drawable.common_layer_seekbar_progress_black)
        //
        animateToStart()
    }

    private fun animateToStart(){
        mBinding.root.setTranslationY(ApplicationContext.dp2px(mAnimHeight).toFloat())
        mBinding.root.animate().translationY(0f).setDuration(mAnimTime).start()
    }

    private fun animateToFinish(){
        mBinding.root.animate()
            .translationY(ApplicationContext.dp2px(mAnimHeight).toFloat())
            .setDuration(mAnimTime)
            .withEndAction(Runnable {
                finish()
            })
            .start()
    }

    override fun onBackPressed() {
        animateToFinish()
    }

    private fun animateCardView(isZoomOut:Boolean){
        if(isZoomOutCardView != isZoomOut){
            isZoomOutCardView= isZoomOut
            if (isZoomOutCardView) {
                zoomOutCardView()
            }else{
                zoomInCardView()
            }
        }
    }

    private fun zoomInCardView(){
        mBinding.cardView.animate().scaleX(1F).scaleY(1F).setDuration(mAnimTime).start()
    }

    private fun zoomOutCardView(){
        mBinding.cardView.animate().scaleX(0.8F).scaleY(0.8F).setDuration(mAnimTime).start()
    }

    private fun setCoverUrl(url:String){
        Monet.get(ApplicationContext.instance())
            .load<GlideConfig>(url)
            .placeholder(com.sense.kukoo.common.R.mipmap.common_icon_default_editor_picks)
            .into(mBinding.ivMusicIcon)
    }

    private fun setSubscribeBtnState(isSub:Boolean){
        if(isSubscribe != isSub){
            isSubscribe = isSub
            if (isSub) {
                //订阅
                mBinding.bgBtnSubscribe.setImageResource(com.sense.kukoo.common.R.drawable.common_icon2_sub_off_28dp)
            }else{
                //未订阅
                mBinding.bgBtnSubscribe.setImageResource(com.sense.kukoo.common.R.drawable.common_icon2_sub_on_28dp)
            }
        }
    }

    private fun setLikeState(isL:Boolean){
        if (isLike!=isL){
            isLike = isL
            if(isLike){
                mBinding.ivBtnHeart.setImageResource(com.sense.kukoo.common.R.drawable.common_icon_heart_red)
            }else{
                mBinding.ivBtnHeart.setImageResource(com.sense.kukoo.common.R.drawable.common_icon_heart_black)
            }
        }
    }

    private val mlistener = object : UserWatcher.MusicStateWatcher{

        override fun onMusicChanged(music: LocalMediaListItemBean) {
            LoggerManager.d(TAG,"onMusicChanged - music.idOfBooks()=${music.idOfBooks()}")
            mCurrentMusic = music
            mViewModel.setCurrentMusic(music)
            //
            setCoverUrl(mCurrentMusic.coverOfChapter())
            mBinding.tvTitle.setText(mCurrentMusic.titleOfChapter())
            mBinding.tvTitleFirst.setText(mCurrentMusic.titleOfBooks())
            //
            mViewModel.loadSubscribeAndLikeState()
        }

        override fun onPlayTimeChanged(currentInt:Int, totalInt:Int, current:String, total:String) {
            mBinding.tvTimeCurrent.setText(current)
            mBinding.tvTimeTotal.setText(total)
            if (!isSeekBarTracking) {
                mBinding.seekBar.max = totalInt
                mBinding.seekBar.progress = currentInt
            }
        }

        override fun onPlayPercentChanged(percent: Int) {}

        override fun onPlayStateChanged(s: Int) {
            state = s
            LoggerManager.d(TAG,"onPlayStateChanged() state=${state}")
            when (state) {
                UserWatcher.MusicStateWatcher.STATE_NOT_PLAYING ->{
                    //无播放内容
                    animateToFinish()
                }
                /*UserWatcher.MusicStateWatcher.STATE_SEEKING,*/
                UserWatcher.MusicStateWatcher.STATE_ERROR_RETRYING,
                UserWatcher.MusicStateWatcher.STATE_PREPARE,
                UserWatcher.MusicStateWatcher.STATE_PLAYING ->{
                    animateCardView(false)
                    mBinding.ivBtnPlay.setImageResource(com.sense.kukoo.common.R.drawable.common_icon_play_stoped2)
                }
                UserWatcher.MusicStateWatcher.STATE_PAUSE ->{
                    animateCardView(true)
                    mBinding.ivBtnPlay.setImageResource(com.sense.kukoo.common.R.drawable.common_icon_play_start)
                }
                else ->{
                    LoggerManager.e(TAG, "mlistener.onPlayStateChanged state=${state} 不响应")
                }
            }
        }

        override fun onPlaySpeedChanged(speed: Float) {
            //
            this@MediaControlerActivity.speed = speed
            when (speed) {
                UserWatcher.MusicStateWatcher.SPEED_1P0 -> {
                    mBinding.tvBtnTimes.setText(com.sense.kukoo.common_i18n.R.string.media_controler_speed_1p0)
                    mBinding.tvBtnTimes.setTextColor(ApplicationContext.getColor(com.sense.kukoo.common.R.color.android_black))
                }
                UserWatcher.MusicStateWatcher.SPEED_2P0 -> {
                    mBinding.tvBtnTimes.setText(com.sense.kukoo.common_i18n.R.string.media_controler_speed_2p0)
                    mBinding.tvBtnTimes.setTextColor(ApplicationContext.getColor(com.sense.kukoo.common.R.color.dialog_btn_text_color_red))
                }
                UserWatcher.MusicStateWatcher.SPEED_1P2 -> {
                    mBinding.tvBtnTimes.setText(com.sense.kukoo.common_i18n.R.string.media_controler_speed_1p2)
                    mBinding.tvBtnTimes.setTextColor(ApplicationContext.getColor(com.sense.kukoo.common.R.color.dialog_btn_text_color_red))
                }
                UserWatcher.MusicStateWatcher.SPEED_1P5 -> {
                    mBinding.tvBtnTimes.setText(com.sense.kukoo.common_i18n.R.string.media_controler_speed_1p5)
                    mBinding.tvBtnTimes.setTextColor(ApplicationContext.getColor(com.sense.kukoo.common.R.color.dialog_btn_text_color_red))
                }
                UserWatcher.MusicStateWatcher.SPEED_0P8 -> {
                    mBinding.tvBtnTimes.setText(com.sense.kukoo.common_i18n.R.string.media_controler_speed_0p8)
                    mBinding.tvBtnTimes.setTextColor(ApplicationContext.getColor(com.sense.kukoo.common.R.color.dialog_btn_text_color_red))
                }
                else -> {}
            }
        }

        override fun onPlayListChanged() {}
    }

    private val mTimerlistener = object : UserWatcher.TimerStateWatcher{
        override fun onTimerChanged(type: Int, left: Long, leftStr:String) {
            if(left<=0){
                mBinding.ivBtnTimerText.text = ""
            }else{
                mBinding.ivBtnTimerText.text = leftStr
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: SubscriptionChangedEvent) {
        if(event.from != SubscriptionChangedEvent.FROM_CONTROLER && mCurrentMusic.idOfBooks() == event.bookId){
            setSubscribeBtnState(event.isSubscribe)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: LoginSuccessEvent) {
        mViewModel.loadSubscribeAndLikeState()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: LogoutEvent) {
        mViewModel.loadSubscribeAndLikeState()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Kukoo.watcher.register(mlistener)
        Kukoo.watcher.registerTimerWatcher(mTimerlistener)
        EventBus.getDefault().register(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        Kukoo.watcher.unregister(mlistener)
        Kukoo.watcher.unregisterTimerWatcher(mTimerlistener)
        EventBus.getDefault().unregister(this)
    }
}